package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.FangGoldService;
import com.meirengu.utils.HttpUtil;
import com.meirengu.webview.model.KwFjsPush;
import com.meirengu.webview.model.KwFjsPushLog;
import com.meirengu.webview.service.KwFjsPushLogService;
import com.meirengu.webview.service.KwFjsPushService;
import com.meirengu.webview.utils.ConfigUtil;
import com.meirengu.webview.utils.Unicode;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.*;

import static com.meirengu.webview.common.ConfigConsts.CHANNEL_CODE_JUEDAI;
import static com.meirengu.webview.common.ConfigConsts.CHANNEL_NAME_JUEDAI;
import static com.meirengu.webview.common.Constants.*;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;

/**
 * 房金所
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class FangGoldServiceImpl implements FangGoldService {

    Logger logger = LoggerFactory.getLogger(FangGoldServiceImpl.class);

    @Autowired
    private KwFjsPushService kwFjsPushService;

    @Autowired
    private KwFjsPushLogService kwFjsPushLogService;

    /**
     * @param
     * @return
     */

    public Integer applyLoan(String telephonenumber, String name, String loanAmount,
                             String city, String duration) throws Exception {

        String url = ConfigUtil.getConfig("fanggold.url");
        String key = ConfigUtil.getConfig("fanggold.key");
        url = url + key;

        Map<String, String> params = new HashMap<>();
        params.put("telephonenumber", telephonenumber);
        params.put("name", name);
        params.put("loan_amount", loanAmount);
        params.put("city", city);
        params.put("duration", duration);

        //接口调用信息表
        KwFjsPush kwFjsPush = new KwFjsPush();
        kwFjsPush.setInterfaceCode("fjs");
        kwFjsPush.setInterfaceName("房金所");
        kwFjsPush.setMobile(telephonenumber);
        kwFjsPush.setCode(BUSINESS_STATUS_FAIL);


        KwFjsPushLog kwFjsPushLog = new KwFjsPushLog();
        kwFjsPushLog.setInterfaceCode("fjs");
        kwFjsPushLog.setInterfaceName("房金所");
        kwFjsPushLog.setMobile(telephonenumber);
        kwFjsPushLog.setSendUrl(url.toString());
        kwFjsPushLog.setParams(params.toString());


        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPostForm(url, params);
            int code = hr.getStatusCode();
            if (code == 200) {
                kwFjsPushLog.setBackUrl(hr.toString());
                kwFjsPushLog.setHttpCode(200);
                kwFjsPushLog.setHttpContent(hr.toString());

                logger.info("==FangGoldServiceImpl.applyLoan request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("errNum");
                String rMsg = returnMsg.getString("errMsg");
                if ("0".equals(rCode)) {
                    kwFjsPush.setCode(BUSINESS_STATUS_SUCCESS);
                    kwFjsPush.setMessage("成功");
                    logger.info("==FangGoldServiceImpl.applyLoan business success");
                } else {
                    kwFjsPush.setCode(BUSINESS_STATUS_OTHER);
                    kwFjsPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==FangGoldServiceImpl.applyLoan business fail");
                }
            } else {
                kwFjsPushLog.setBackUrl(hr.toString());
                kwFjsPushLog.setHttpCode(code);
                kwFjsPushLog.setHttpContent(hr.toString());
                logger.warn("==FangGoldServiceImpl.applyLoan request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwFjsPushLog.setHttpCode(408);
            kwFjsPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwFjsPushService.insert(kwFjsPush);
            kwFjsPushLog.setPushId(kwFjsPush.getId());
            kwFjsPushLogService.insert(kwFjsPushLog);
            return kwFjsPush.getCode();
        }


    }

    @Override
    public Integer applyLoanYiJu(String telephonenumber, String name, String birthday, String sex) throws Exception {
        String url = ConfigUtil.getConfig("yiju.url");
        String productId = ConfigUtil.getConfig("yiju.product.id");
        String productCode = ConfigUtil.getConfig("yiju.product.code");
        String providerCode = ConfigUtil.getConfig("yiju.provider.code");
        String mediaSource = ConfigUtil.getConfig("yiju.media.source");

        Map<String, String> params = new HashMap<>();
        params.put("productId", productId);
        params.put("productCode", productCode);
        params.put("providerCode", providerCode);
        params.put("mediaSource", mediaSource);

        params.put("phone", telephonenumber);
        params.put("name", name);
        params.put("sex", sex);
        params.put("birthday", birthday);

        //接口调用信息表
        KwFjsPush kwFjsPush = new KwFjsPush();
        kwFjsPush.setInterfaceCode("yiju");
        kwFjsPush.setInterfaceName("熠巨");
        kwFjsPush.setMobile(telephonenumber);
        kwFjsPush.setCode(BUSINESS_STATUS_FAIL);


        KwFjsPushLog kwFjsPushLog = new KwFjsPushLog();
        kwFjsPushLog.setInterfaceCode("yiju");
        kwFjsPushLog.setInterfaceName("熠巨");
        kwFjsPushLog.setMobile(telephonenumber);
        kwFjsPushLog.setSendUrl(url.toString());
        kwFjsPushLog.setParams(params.toString());


        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPostForm(url, params);
            int code = hr.getStatusCode();
            String hrStr = hr.toString();
            hrStr = Unicode.unicodeToCn(hrStr);
            if (code == 200) {
                kwFjsPushLog.setBackUrl(hrStr);
                kwFjsPushLog.setHttpCode(200);
                kwFjsPushLog.setHttpContent(hrStr);

                logger.info("==FangGoldServiceImpl.applyLoanYiJu request success. result:{}", hr.toString());
                String content = hr.getContent();
                content = Unicode.unicodeToCn(content);
                JSONObject returnMsg = JSONObject.parseObject(content);
                JSONObject data = returnMsg.getJSONObject("data");
                String rCode = returnMsg.getString("ecode");
                String rMsg = data.getString("status");
                if ("0".equals(rCode) && rMsg.contains("提交成功")) {
                    kwFjsPush.setCode(BUSINESS_STATUS_SUCCESS);
                    kwFjsPush.setMessage("成功");
                    logger.info("==FangGoldServiceImpl.applyLoanYiJu business success");
                } else {
                    kwFjsPush.setCode(BUSINESS_STATUS_OTHER);
                    kwFjsPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==FangGoldServiceImpl.applyLoanYiJu business fail");
                }
            } else {
                kwFjsPushLog.setBackUrl(hr.toString());
                kwFjsPushLog.setHttpCode(code);
                kwFjsPushLog.setHttpContent(hr.toString());
                logger.warn("==FangGoldServiceImpl.applyLoanYiJu request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwFjsPushLog.setHttpCode(408);
            kwFjsPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwFjsPushService.insert(kwFjsPush);
            kwFjsPushLog.setPushId(kwFjsPush.getId());
            kwFjsPushLogService.insert(kwFjsPushLog);
            return kwFjsPush.getCode();
        }
    }

    @Override
    public Integer applyLoanYiJuFz(String telephonenumber, String name, String birthday, String sex) throws Exception {
        String url = ConfigUtil.getConfig("yiju.url");
        String productId = ConfigUtil.getConfig("yijufz.product.id");
        String productCode = ConfigUtil.getConfig("yijufz.product.code");
        String providerCode = ConfigUtil.getConfig("yijufz.provider.code");
        String mediaSource = ConfigUtil.getConfig("yijufz.media.source");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("备注", "信贷平台；用户注册信贷平台时附赠；熠巨赠险1");

        Map<String, String> params = new HashMap<>();
        params.put("productId", productId);
        params.put("productCode", productCode);
        params.put("providerCode", providerCode);
        params.put("mediaSource", mediaSource);

        params.put("phone", telephonenumber);
        params.put("name", name);
        params.put("sex", sex);
        params.put("birthday", birthday);
        params.put("otherMsg", jsonObject.toJSONString());

        //接口调用信息表
        KwFjsPush kwFjsPush = new KwFjsPush();
        kwFjsPush.setInterfaceCode("yijufz");
        kwFjsPush.setInterfaceName("熠巨方正");
        kwFjsPush.setMobile(telephonenumber);
        kwFjsPush.setCode(BUSINESS_STATUS_FAIL);


        KwFjsPushLog kwFjsPushLog = new KwFjsPushLog();
        kwFjsPushLog.setInterfaceCode("yijufz");
        kwFjsPushLog.setInterfaceName("熠巨方正");
        kwFjsPushLog.setMobile(telephonenumber);
        kwFjsPushLog.setSendUrl(url.toString());
        kwFjsPushLog.setParams(params.toString());


        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPostForm(url, params);
            int code = hr.getStatusCode();
            String hrStr = hr.toString();
            hrStr = Unicode.unicodeToCn(hrStr);
            if (code == 200) {
                kwFjsPushLog.setBackUrl(hrStr);
                kwFjsPushLog.setHttpCode(200);
                kwFjsPushLog.setHttpContent(hrStr);

                logger.info("==FangGoldServiceImpl.applyLoanYiJuFz request success. result:{}", hr.toString());
                String content = hr.getContent();
                content = Unicode.unicodeToCn(content);
                JSONObject returnMsg = JSONObject.parseObject(content);
                JSONObject data = returnMsg.getJSONObject("data");
                String rCode = returnMsg.getString("ecode");
                String rMsg = data.getString("status");
                if ("0".equals(rCode) && rMsg.contains("提交成功")) {
                    kwFjsPush.setCode(BUSINESS_STATUS_SUCCESS);
                    kwFjsPush.setMessage("成功");
                    logger.info("==FangGoldServiceImpl.applyLoanYiJuFz business success");
                } else {
                    kwFjsPush.setCode(BUSINESS_STATUS_OTHER);
                    kwFjsPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==FangGoldServiceImpl.applyLoanYiJu business fail");
                }
            } else {
                kwFjsPushLog.setBackUrl(hr.toString());
                kwFjsPushLog.setHttpCode(code);
                kwFjsPushLog.setHttpContent(hr.toString());
                logger.warn("==FangGoldServiceImpl.applyLoanYiJuFz request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwFjsPushLog.setHttpCode(408);
            kwFjsPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwFjsPushService.insert(kwFjsPush);
            kwFjsPushLog.setPushId(kwFjsPush.getId());
            kwFjsPushLogService.insert(kwFjsPushLog);
            return kwFjsPush.getCode();
        }
    }

    @Override
    public Integer applyJuedai(String mobile, String name, String idCard, String loanStartLimit, String loanTerm, String loanPurpose
            , String identityType, String isWeiliD, String isInsurance, String isCreditCard, String property, String carProduction
            , String city, String income, String workYears, String businessLife, String isSecurity, String isFund
            , String operationYears, String isLicense, String flag, String ip) {
        String appId = ConfigUtil.getConfig("juedai.appId");

        String encoding = "UTF-8";

        String baseUrl = ConfigUtil.getConfig("juedai.url");
        String tokenUrl = baseUrl + "/open/getUserToken";
        String pushUrl = baseUrl + "/open/transCreditinfo";

        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("appId", appId);
        String sign1 = createSign(encoding, paramsMap, appId);

        String token = getToken(tokenUrl + "?appId=" + appId + "&characterEncoding=" + encoding + "&sign=" + sign1);

        KwFjsPush kwFjsPush;
        KwFjsPushLog kwFjsPushLog = null;

        if (isNotEmpty(token)) {
            Map<String, String> params = new HashMap<>();
            params.put("appId", appId);

            params.put("mobile", mobile);
            params.put("name", name);

            if (isNotEmpty(idCard)) {
                params.put("idCard", idCard);
            }

            params.put("loanStartLimit", loanStartLimit);
            params.put("loanTerm", loanTerm);
            params.put("loanPurpose", loanPurpose);
//            params.put("isInterest", "");
//            params.put("isWorryMoney", "");
//            params.put("education", "");
            params.put("identityType", identityType);
//            params.put("creditHistory", "");
//            params.put("liabilities", "");
            params.put("isWeiliD", isWeiliD);
            params.put("isInsurance", isInsurance);
            params.put("isCreditCard", isCreditCard);
//            params.put("sesameCredit", "");
            params.put("property", property);
            params.put("carProduction", carProduction);
//            params.put("isMortgageHouse", "");
//            params.put("isMortgageCar", "");
//            params.put("isNeedInsurance", "");
            params.put("city", city);
//            params.put("companyName", "");
            params.put("income", income);
            params.put("workYears", workYears);
            params.put("businessLife", businessLife);
            params.put("isSecurity", isSecurity);
            params.put("isFund", isFund);
//            params.put("amount", "");

            if (isNotEmpty(operationYears)) {
                params.put("operationYears", operationYears);
            }

            if (isNotEmpty(isLicense)) {
                params.put("isLicense", isLicense);
            }

            params.put("flag", flag);
            params.put("ip", ip);

            String sign = createSign(encoding, params, appId);

            params.put("sign", sign);
            params.put("characterEncoding", encoding);
            params.put("token", token);

            //接口调用信息表
            kwFjsPush = new KwFjsPush();
            kwFjsPush.setInterfaceCode(CHANNEL_CODE_JUEDAI);
            kwFjsPush.setInterfaceName(CHANNEL_NAME_JUEDAI);
            kwFjsPush.setMobile(mobile);
            kwFjsPush.setCode(BUSINESS_STATUS_FAIL);

            kwFjsPushLog = new KwFjsPushLog();
            kwFjsPushLog.setInterfaceCode(CHANNEL_CODE_JUEDAI);
            kwFjsPushLog.setInterfaceName(CHANNEL_NAME_JUEDAI);
            kwFjsPushLog.setMobile(mobile);
            kwFjsPushLog.setSendUrl(pushUrl);
            kwFjsPushLog.setParams(params.toString());

            HttpUtil.HttpResult hr = HttpUtil.doPostForm2(pushUrl, params);
            int statusCode = hr.getStatusCode();

            kwFjsPushLog.setBackUrl(hr.toString());
            kwFjsPushLog.setHttpCode(statusCode);
            kwFjsPushLog.setHttpContent(hr.getContent());

            if (statusCode == 200) {
                String content = hr.getContent();

                if (isNotEmpty(content)) {
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    String code = jsonObject.getString("code");
                    String msg = jsonObject.getString("msg");

                    if (StringUtils.equals(code, "200")) {
                        kwFjsPush.setCode(BUSINESS_STATUS_SUCCESS);
                        kwFjsPush.setMessage("成功");
                    } else {
                        kwFjsPush.setCode(BUSINESS_STATUS_OTHER);
                        kwFjsPush.setMessage("code: " + code + ",msg:" + msg);
                    }
                } else {
                    kwFjsPush.setCode(BUSINESS_STATUS_FAIL);
                }
            } else {
                kwFjsPush.setCode(BUSINESS_STATUS_FAIL);
            }
        } else {
            kwFjsPush = new KwFjsPush();
            kwFjsPush.setInterfaceCode(CHANNEL_CODE_JUEDAI);
            kwFjsPush.setInterfaceName(CHANNEL_NAME_JUEDAI);
            kwFjsPush.setMobile(mobile);
            kwFjsPush.setCode(BUSINESS_STATUS_FAIL);
            kwFjsPush.setMessage("token为空");
            kwFjsPushService.insert(kwFjsPush);
        }

        kwFjsPushService.insert(kwFjsPush);
        if (kwFjsPushLog != null) {
            kwFjsPushLog.setPushId(kwFjsPush.getId());
            kwFjsPushLogService.insert(kwFjsPushLog);
        }

        return kwFjsPush.getCode();
    }

    private String createSign(String characterEncoding, Map<String, String> paramsMap, String key) {
        Map<String, Object> treeMap = new TreeMap<>(paramsMap);

        String sign = "";
        try {
            StringBuffer sb = new StringBuffer();
            Set es = treeMap.entrySet();
            Iterator it = es.iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String k = (String) entry.getKey();
                Object v = entry.getValue();
                if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                    sb.append(k + "=" + v + "&");
                }
            }
            sb.append("key=" + key);
            Mac hasher = Mac.getInstance("HmacSHA256");
            hasher.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
            byte[] hash = hasher.doFinal(sb.toString().getBytes(characterEncoding));
            sign = DatatypeConverter.printHexBinary(hash);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign.toLowerCase();
    }

    private String getToken(String tokenUrl) {
        HttpUtil.HttpResult hr = HttpUtil.doGet2(tokenUrl);

        if (hr != null & hr.getStatusCode() == 200) {
            String content = hr.getContent();
            if (isNotEmpty(content)) {
                JSONObject jsonObject = JSONObject.parseObject(content);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    return jsonObject.getString("token");
                }
            }
        }
        return "";
    }

}
